import { Component, OnInit, Input, Output, EventEmitter, ElementRef, SimpleChanges } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';
import { Router } from "@angular/router";

declare var $: any;
var pinyin = require("pinyin");
@Component({
	selector: 'sa-company-tree-checkbox',
	templateUrl: './companyTreeCheckbox.component.html',
	styleUrls: ['./companyTreeCheckbox.component.css'],
})
export class CompanyTreeCheckboxComponent implements OnInit {
	@Input() companyTreeId: string; //公司树标识Id
	@Input() wrap: any; //事件页面根元素
	@Input() wrapId: any; //事件页面根元素Id
	@Input() companyData: any; //父组件公司数据
	@Input() companyValue: any; //绑定公司[companyName,companyId]
	@Input() Height: number; //高度
	@Input() inputName: string = 'companyName'; //校验使用的公司名称;默认name="companyName"
	@Input() placeholder: string = '请选择'; //弱提示语
	@Input() inputParam: any = {}; //接口参数
	@Input() inputApi: string = 'company/companytree.html'; //接口参数
	@Input() filterNoChildLevel: boolean = false; //无子级不展示
	@Input() companyParentList: any; //父级公司数据
	@Output() companySelected = new EventEmitter();
	@Output() confirm  = new EventEmitter(); // 确认选择
	private companyCode: string = ''; //选中的公司code
	companyNameSelectedList: any = []; //选中的公司名称(多选)
	private companyIdSelectedList: any = []; //选中的公司ID(多选)
	private companySelectedList: any = []; //选中的公司(多选)
	private companyList: any = []; //公司数据
	clearTimer: any = '' // 定时器id
	@Input() threeState: boolean = true; //关联父子级
	@Input() opened: boolean = true; //是否展开全部节点
	@Input() isShowChildData: boolean = true; //是否显示子节点数据
	selectIndex: any = '' // 选中的位置
	selectCount: any = '' // 选中的总数
	constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) { }
	//传参给父组件
	sendParent() {
		let companyInfo = {
			'companyCode': this.companyCode,
			'companyList': this.companyList,
			'companyNameSelectedList': this.companyNameSelectedList,
			'companyIdSelectedList': this.companyIdSelectedList,
			'companySelectedList': this.companySelectedList,
		}
		this.companySelected.emit(companyInfo);
	}
	ngOnInit() {
		// System.import('assets/js/jstree/jstree.min.js').then(() => {
		// 	this.initCompanyList();
		//			this.companyCilckEvent();
		// })
	}
	ngOnChanges(changes: SimpleChanges) {
		if (this.companyValue && this.companyValue.length > 0) {
			this.companyNameSelectedList = [];
			this.companyIdSelectedList = [];
			this.companySelectedList = [];
			for (let item of this.companyValue) {
				this.companyNameSelectedList.push(item.companyName);
				this.companyIdSelectedList.push(item.companyId);
			}
			this.companySelectedList = this.companyValue;
			$('#' + this.companyTreeId).find('.tree_company_input').val(this.companyNameSelectedList.join(',')).change();
			this.sendParent();
		} else {
			this.companyNameSelectedList = [];
			this.companyIdSelectedList = [];
			this.companySelectedList = [];
			$('#' + this.companyTreeId).find('.tree_company_input').val('')
			this.sendParent();
		}
	}
	//页面点击事件监听
	companyCilckEvent() {
		let companyTreeM = document.getElementById(this.companyTreeId);
		let tree_box = companyTreeM.getElementsByClassName('s_tree_box')[0];
		let company = companyTreeM.getElementsByClassName('tree_company_input')[0];
		let wrap;
		if (this.wrapId) {
			wrap = document.getElementById(this.wrapId)
		} else {
			if (this.wrap == 'body') {
				wrap = document.getElementsByTagName('body')[0];
			} else if (this.wrap == 'html') {
				wrap = document.getElementsByTagName('html')[0];
			} else {
				wrap = document;
			}
		}
		wrap.onclick = null;
		wrap.onclick = function (e: any) {
			if (tree_box.contains(e.target) || e.target == company) { //判断点击是否在下拉框内
				// 如果确认按钮-关闭
				if (e.target.className == 'btn btn-primary') {
					tree_box.className = tree_box.className.replace("tree_open", "");
				}
			} else {
				tree_box.className = tree_box.className.replace("tree_open", "");
				$('#' + this.companyTreeId).find('.treeSearchInput').val('')
			}

		}.bind(this)
	}
	ngOnDestroy() {
		let wrap: any = this.wrapId ? document.getElementById(this.wrapId) : (this.wrap ? document.getElementsByTagName(this.wrap) : document);;
		wrap.onclick = null;
	}
	// 渲染数据
	reloadJsTree(type) {
		if (type == 'load') { // 渲染勾选项
			// $('#' + this.companyTreeId).jstree("uncheck_all")
			for (let item of this.companyList) {
				item.state.selected = false;
				for (let lis of this.companyIdSelectedList) {
					if (item.id == lis) {
						item.state.selected = true;
					}
				}
			}
			this.isAllSelect = this.companyList.length === this.companyIdSelectedList.length
		} else if (type == 'reset') {   // 清空勾选项
			for (let item of this.companyList) {
				item.state.selected = false;
			}
			this.isAllSelect = false
		}
	}
	//拉取公司数据,生成树形图
	initCompanyList(type) {
		// 销毁 jsTree
		$('#' + this.companyTreeId).find('.treeId').eq(0).jstree("destroy");
		var that = this;
		$('#' + this.companyTreeId).find('.treeId').eq(0).data('jstree', false).empty().jstree({
			"core": {
				'data': function (obj, callback) {
					var jsonstr = "[]";
					var jsonarray = eval('(' + jsonstr + ')');
					// if(that.companyParentList == undefined || that.companyParentList.length == 0){
					$.ajax({
						type: "POST",
						url: config.BaseURL + that.inputApi,
						dataType: "json",
						cache: false,
						xhrFields: {
							withCredentials: true
						},
						timeout: 30000,
						data: that.inputParam,
						success: function (result) {
							// 增加公司拼音字段
							var forData = result.data ? result.data : result;
							var newChildArr = []
							if (forData.length && Array.isArray(forData)) {
								for (let i = 0; i < forData.length; i++) {
									if (!that.opened) {
										forData[i].state.opened = false
									}
									forData[i].text = forData[i].text + `<span style="display: none;">${pinyin(forData[i].text, { style: pinyin.STYLE_NORMAL }).join('')}</span>`
								}

								if (!that.isShowChildData) {
									for (let j = 0; j < forData.length; j++) {
										if (forData[j].parent == '#') {
											newChildArr.push(forData[j])
										}

									}

									that.companyList = newChildArr;
								} else {
									// 是否无子级不展示
									if (that.filterNoChildLevel){
										let resultTree = result.data ? result.data : result
										let filterData = resultTree.filter(ele => ele.parent != '#')
										let parentData = resultTree.filter(ele => filterData.some(item => ele.parent == '#' && ele.id == item.parent))
										that.companyList = [...filterData, ...parentData]
									}else {
										that.companyList = result.data ? result.data : result;
									}
								}

								that.reloadJsTree(type);
								that.companyParentList = that.companyList;
								jsonarray = that.companyList;
								callback.call(this, jsonarray);
							}


						},
						error: function (data, errorMsg) {
							if (data.statusText === 'timeout') {
								this.jsonApiService.message('请求超时,请重试')
							} else {
								common.clearCookie('isLogin');
								common.clearCookie('WEBSIDE_SID');
								localStorage.clear();
								this.router.navigate(['/auth']);
							}
						}
					});
					// }else{
					// 	that.companyList = that.companyParentList;
					//     that.reloadJsTree(type);
					// 	for(let i = 0; i < that.companyParentList.length; i++) {
					// 		that.companyParentList[i].text = that.companyParentList[i].text + `<span style="display: none;">${pinyin(that.companyParentList[i].text,{style: pinyin.STYLE_NORMAL}).join('')}</span>`
					// 	}
					// 	callback.call(this, that.companyList);
					// }

				},
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 100,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": that.threeState, //父子级别级联选择
				"cascade": that.threeState ? "down" : "undetermined"
			},
			"plugins": ["search", "checkbox"]
		})
	}
	// 确认所选值
	submitCompanyValue() {
		const that = this;
		var tree = $('#' + this.companyTreeId).find('.treeId').eq(0).jstree();
		this.companySelectedList = [];
		this.companyNameSelectedList = [];
		this.companyIdSelectedList = [];
		// var selectedIds = tree.get_checked();   //获取所有选中节点id
		var selected = tree.get_checked(true);  //获取所有选中节点数据

		for (let item of selected) {
			let obj = {
				companyId: item.id,
				companyName: item.text.substring(0, item.text.indexOf('<')), // 获取内容前删除添加的拼音字段
				parent: item.parent
			}
			this.companyNameSelectedList.push(item.text.substring(0, item.text.indexOf('<')));
			this.companyIdSelectedList.push(item.id);
			this.companySelectedList.push(obj);
		}
		$('#' + this.companyTreeId).find('.tree_company_input').val(this.companyNameSelectedList.join(',')).change();
		this.sendParent();

		const companyInfo = {
			'companyCode': this.companyCode,
			'companyList': this.companyList,
			'companyNameSelectedList': this.companyNameSelectedList,
			'companyIdSelectedList': this.companyIdSelectedList,
			'companySelectedList': this.companySelectedList,
		}
		this.confirm.emit(companyInfo);

		if ($('#' + that.companyTreeId).find('.jstree-searchCheck').length > 0) {
			if ($('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className == 'jstree-anchor jstree-search jstree-searchCheck' ||
				$('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className == 'jstree-anchor jstree-searchCheck jstree-hovered jstree-clicked') {
				$('#' + that.companyTreeId).find('.s_tree_box')[0].className = "s_tree_box";
				that.selectIndex = '';
				that.selectCount = '';
			}
		} else {
			// console.log(that.companyIdSelectedList)
			// if(that.companyName){
			// 	$('#' + that.companyTreeId).find('.s_tree_box')[0].className = "s_tree_box";
			// }
		}
	}
	// 重置[清空选值]
	resetCompanyValue() {
		this.initCompanyList('reset');
	}
	//擦除公司所选值
	delText() {
		this.companyNameSelectedList = [];
		this.companyIdSelectedList = [];
		this.companySelectedList = [];
		$('#' + this.companyTreeId).find('.tree_company_input').val("").change();
		this.companySearch();
		if ($('#' + this.companyTreeId).find('.s_tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#' + this.companyTreeId).find('.tree_company_input').focus();
		}
		this.sendParent()
		this.selectIndex = '';
		this.selectCount = '';
		if ($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0) {
			if ($('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className.indexOf('jstree-clicked') != -1) {
				$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor jstree-clicked";
			} else {
				$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor";
			}
		}
	}
	//打开公司树
	companyClick(e) {
		var treeBox = $('.s_tree_box');
		for (var i = 0; i < treeBox.length; i++) {
			if (e.target.parentNode.parentNode.parentNode.id != this.companyTreeId) {
				treeBox[i].className = treeBox[i].className.replace("tree_open", "");
			}
		}
		if ($('#' + this.companyTreeId).find('.s_tree_box')[0].className.indexOf('tree_open') < 0) {
			System.import('assets/js/jstree/jstree.min.js').then(() => {
				this.initCompanyList('load');
				this.companyCilckEvent();
			})
		}
		$('#' + this.companyTreeId).find('.s_tree_box').toggleClass('tree_open');
		$('#' + this.companyTreeId).find('.treeSearchInput').val('');
		this.selectIndex = '';
		this.selectCount = '';
		// if($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0){
		// 	$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor"
		// }
	}
	//公司树模糊搜索
	companySearch() {
		var that = this;
		var value = $('#' + this.companyTreeId).find('.treeSearchInput').val();

		that.selectIndex = '';
		that.selectCount = '';
		for (var j = 0; j < $('#' + this.companyTreeId).find('.jstree-anchor').length; j++) {
			if ($('#' + this.companyTreeId).find('.jstree-anchor')[j].className.indexOf('jstree-clicked') != -1) {
				$('#' + this.companyTreeId).find('.jstree-anchor')[j].className = "jstree-anchor jstree-clicked";
			} else {
				$('#' + this.companyTreeId).find('.jstree-anchor')[j].className = "jstree-anchor";
			}

		}

		if (this.clearTimer) { clearTimeout(this.clearTimer); }
		this.clearTimer = setTimeout(function () {
			const companyTreeDom = $('#' + that.companyTreeId).find('.treeId').eq(0)
			if (companyTreeDom[0].className.indexOf('jstree') != -1) {
				companyTreeDom.jstree(true).search(value);
			}
			let searchResult = $('#' + that.companyTreeId).find('.jstree-search').length;
			if (searchResult < 1) {
				return;
			}

			if (value) {
				that.selectIndex = 1;
				that.selectCount = $('#' + that.companyTreeId).find('.jstree-search').length;
				if ($('#' + that.companyTreeId).find('.jstree-search')[0].className.indexOf('jstree-clicked') != -1) {
					$('#' + that.companyTreeId).find('.jstree-search')[0].className = "jstree-anchor jstree-search jstree-searchCheck jstree-clicked";
				} else {
					$('#' + that.companyTreeId).find('.jstree-search')[0].className = "jstree-anchor jstree-search jstree-searchCheck";
				}


			}

			$('#' + that.companyTreeId).find('.jstree-search').each(function (index, obj) {
				if (index < 1) { //js树搜索定位到结果的第一个地方；
					let container = $('#' + that.companyTreeId).find('.vision_tree');
					let scrollTo = $(this);
					container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
					container.animate({
						scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
					});
				}
			})
		}, 250)
	}
	upArrow() {
		var that = this;
		if (parseInt(this.selectIndex) == 1) {
			that.jsonApiService.message("目前已经在开始位置");
			return;
		}
		if ($('#' + this.companyTreeId).find('.jstree-searchCheck')[0]) {
			that.selectIndex = parseInt(that.selectIndex) - 1;
			if ($('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex - 1].className.indexOf('jstree-clicked') != -1) {
				$('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex - 1].className = "jstree-anchor jstree-search jstree-searchCheck jstree-clicked"
			} else {
				$('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex - 1].className = "jstree-anchor jstree-search jstree-searchCheck"
			}
			if ($('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className.indexOf('jstree-clicked') != -1) {
				$('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className = "jstree-anchor jstree-search jstree-clicked";
			} else {
				$('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className = "jstree-anchor jstree-search";
			}

			let container = $('#' + that.companyTreeId).find('.vision_tree');
			let _this = $('#' + this.companyTreeId).find('.jstree-search').eq(that.selectIndex - 1);
			let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
			container.animate({ scrollTop: top });
		}


	}
	downArrow() {
		var that = this;
		if (parseInt(this.selectIndex) == parseInt(this.selectCount)) {
			that.jsonApiService.message("目前已经在结束位置");
			return;
		}
		if ($('#' + this.companyTreeId).find('.jstree-searchCheck')[0]) {
			let lenindex = parseInt(this.selectIndex);
			if ($('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className.indexOf('jstree-clicked') != -1) {
				$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor jstree-search jstree-clicked"
			} else {
				$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor jstree-search"
			}
			this.selectIndex = parseInt(this.selectIndex) + 1;
			if ($('#' + this.companyTreeId).find('.jstree-search')[lenindex].className.indexOf('jstree-clicked') != -1) {
				$('#' + this.companyTreeId).find('.jstree-search')[lenindex].className = "jstree-anchor jstree-search jstree-searchCheck jstree-clicked"
			} else {
				$('#' + this.companyTreeId).find('.jstree-search')[lenindex].className = "jstree-anchor jstree-search jstree-searchCheck"
			}


			let container = $('#' + that.companyTreeId).find('.vision_tree');
			let _this = $('#' + this.companyTreeId).find('.jstree-search').eq(lenindex);
			let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
			container.animate({ scrollTop: top });
		}


	}
	//公司树模糊搜索	click
	companySearchBtn() {
		var that = this;
		var value = $('#' + this.companyTreeId).find('.treeSearchInput').val();
		$('#' + this.companyTreeId).find('.treeId').eq(0).jstree(true).search(value);
		let searchResult = $('#' + this.companyTreeId).find('.jstree-search').length;
		if (searchResult < 1) {
			that.jsonApiService.message('未搜索到结果');
			return;
		}
		$('#' + this.companyTreeId).find('.jstree-search').each(function (index, obj) {
			if (index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#' + that.companyTreeId).find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}

	isAllSelect: boolean = false //是否是全部选中
	//全部选中
	allCheckCompanyValue() {
		const that = this;
		let checkList = $('#' + that.companyTreeId).find('.jstree-anchor')
		var tree = $('#' + this.companyTreeId).find('.treeId').eq(0).jstree();
		if (that.isAllSelect) {
			tree.uncheck_all()
		} else {
			tree.check_all()
		}
		that.isAllSelect = !that.isAllSelect
	}
}